import type { Router, RouteRecord } from 'vue-router'
import NProgress from 'nprogress'
import { loadEnv } from '@build/index'
import { createStoreGuard } from './storeGuard'
import { useI18n } from '@/hooks/web/useI18n'

import { createPermissionRouterGuard } from './permissionGuard';
import { ref } from 'vue'

import * as api from '@/api/login'
import setupSignalR from '@/utils/signalr'

export const originalRouteRecords = ref<RouteRecord[]>();

export default function setupRouterGuard(router: Router) {
  originalRouteRecords.value = router.getRoutes()

  createPageGuard(router)
  createProgressGuard(router)
  createStoreGuard(router)
}
function createPageGuard(router: Router) {
  const loadedPageMap = new Map<string, boolean>()
  
  router.beforeEach(async (to, from) => {
    if (to.path === '/redirect' && from.path === '/') {
      await setupSignalR()

      return '/home'
    }

    if (to.path !== '/login' && from.path === '/') {
      await setupSignalR()
    }
    
    to.meta.loaded = !!loadedPageMap.get(to.path)
            
    if (to.path != '/login') {      
      if (to.path != '/oauth') {           
        await createPermissionRouterGuard(router)
      }

      try {
        router.getRoutes().forEach(e => {
          if (e.path == to.path) {
            throw new Error();
          }
        })
      } catch (error) {
        return true
      }   
      
      router.push('/error')
    }
    
    return true;
  })

  router.afterEach(async (to, from) => {        
    if (to.query.uid !== null && to.query.uid !== undefined) {
      let res = await api.getTokenByUid(to.query.uid);
    }
    else if (to.path === '/redirect' && from.path === '/oauth') {
      window.location.reload()
    }

    loadedPageMap.set(to.path, true)

    return true
  })
}

export function createProgressGuard(router: Router) {
  const { t } = useI18n()
  router.beforeEach(async to => {
    if (to.meta.loaded) {
      return true
    }
    const { VITE_APP_TITLE } = loadEnv()
    document.title = to.meta.title
      ? `${t(to.meta.title as string)} | ${VITE_APP_TITLE}`
      : VITE_APP_TITLE
    NProgress.start()
    return true
  })

  router.afterEach(async () => {
    NProgress.done()
    return true
  })
}